package com.tutucms.common.security;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * Created by wangxudong on 2020/10/29.
 *
 * @version: 1.0
 * @modified :
 */
@Slf4j
public class AESUtil {

    //偏移量
    public static final String VIPARA = "1234567876543211";

    /**
     * AES加密
     *
     * @param data 要加密的字符串
     * @param key  加密key
     * @return 加密后的字符串
     */
    public static String encrypt(String data, String key) {
        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(VIPARA.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, iv);
            byte[] encrypted = cipher.doFinal(data.getBytes());

            return Base64.getEncoder().encodeToString(encrypted); //BASE64加密
        } catch (Exception e) {

            log.error(e.getMessage(), e);

            return null;
        }
    }


    /**
     * AES解密
     *
     * @param data 加密后的字符串
     * @param key  加密key
     * @return 解密后的字符串
     */
    public static String decrypt(String data, String key) {
        try {

            byte[] encrypted1 = Base64.getDecoder().decode(data); //BASE64解密
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(VIPARA.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, iv);
            byte[] original = cipher.doFinal(encrypted1);

            return new String(original);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

            return null;
        }
    }
}
